package handler

import (
	"context"
	"net/http"

	"github.com/opentracing/opentracing-go"
	"github.com/uber/jaeger-client-go"

	"github.com/gin-gonic/gin"
)

type Response struct{}

func NewResponse() *Response {
	return &Response{}
}

type ResponseData struct {
	Code    int         `json:"code" binding:"required" example:"1"`      //code:  0 成功; 非0失败;
	Msg     string      `json:"msg" binding:"required" example:"success"` //错误消息
	TraceID string      `json:"traceId" binding:"required"`               //traceId
	Data    interface{} `json:"data" binding:"required"`                  //数据data
}

func (r *Response) SuccessObj(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, data)
}

func (r *Response) Success(c *gin.Context, data interface{}) {

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "success",
		"data":    data,
		"traceId": GetTraceID(c.Request.Context()),
	})
}

func (r *Response) Error(c *gin.Context, err error) {
	msg := err.Error()

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusInternalServerError,
		"msg":     msg,
		"data":    struct{}{},
		"traceId": GetTraceID(c.Request.Context()),
	})
}

// GetTraceID 获取ctx中的traceID
func GetTraceID(ctx context.Context) (traceID string) {
	span := opentracing.SpanFromContext(ctx)
	if span != nil {
		traceID = span.Context().(jaeger.SpanContext).TraceID().String()
	}
	return traceID
}
